package lib

func init() {
	Probs = append(Probs, Problem{
		Num:         63,
		Discription: "从左上角到右下角的路径个数(带障碍)",
		Level:       2,
		Labels: map[string]int{
			"动态规划": 1,
			"空间复用": 1,
		},
	})
}

func UniquePathsWithObstacles(obstacleGrid [][]int) int {
	m := len(obstacleGrid)
	n := len(obstacleGrid[0])
	dp := make([]int, n)
	if obstacleGrid[0][0] == 1 {
		return 0
	} else {
		dp[0] = 1
	}
    
	//确定第一行的dp，如果有障碍，之后的dp全为0
	for j := 1; j < n; j++ {
		if obstacleGrid[0][j] == 1 {
			break
		}
		dp[j] = 1
	}

	for i := 1; i < m; i++ {
		//每换一行时，要先更新dp[0]
		if obstacleGrid[i][0] == 1 {
			dp[0] = 0
		}
		for j := 1; j < n; j++ {
			if obstacleGrid[i][j] == 1 {
				dp[j] = 0
			} else {
				dp[j] += dp[j-1]
			}
		}
	}

	return dp[n-1]
}
